<template>
  <el-dialog v-model="dialogVisible" :title="'创建账号'" width="30%">
    <el-form ref="formRef" :model="userForm" :rules="rules" label-width="100px" style="padding-right: 30px">
      <el-form-item label="用户名：" prop="name">
        <el-input v-model="userForm.name" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="账号：" prop="account">
        <el-input v-model="userForm.account" placeholder="请输入账号"></el-input>
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="userForm.confirmPassword" type="password" placeholder="请输入确认密码" show-password />
      </el-form-item>
      <el-form-item label="手机号：" prop="phone">
        <el-input v-model="userForm.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="性别：" prop="sex">
        <el-select v-model="userForm.sex" placeholder="请输入性别" style="width: 240px">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"
            :disabled="item.disabled" />
        </el-select>
      </el-form-item>
      <el-form-item label="验证码：" prop="captcha">
        <el-input v-model="userForm.captcha" placeholder="请输入验证码" style="width: 140px; margin-right: 10px;"></el-input>
        <el-button :disabled="isCounting" @click="sendVerificationCode">
          {{ isCounting ? `${countdown}秒后重发` : '发送验证码' }}
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { sendSms } from "@/apis/common.js";
import { createAccountAPI } from "@/apis/user.js";

// 状态和引用定义
const dialogVisible = ref(false);
const formRef = ref(null);
const userForm = ref({
  name: "",
  account: "",
  password: "",
  confirmPassword: "",
  phone: "",
  sex: "",
  captcha: "",
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "名称不能为空", trigger: "blur" },
    { min: 2, max: 10, message: "名称为2-10个字符", trigger: "blur" },
  ],
  account: [{ required: true, message: "账号不能为空", trigger: "blur" },
  { min: 5, max: 20, message: "账号为5-20个字符", trigger: "blur" },
  {
    pattern: /^[a-zA-Z0-9_]+$/,
    message: '账号只能包含字母、数字和下划线',
    trigger: 'blur'
  },
  ],
  password: [{ required: true, message: "密码不能为空", trigger: "blur" },
  { min: 6, max: 14, message: "密码为6-14个字符", trigger: "blur" },
  {
    pattern: /^(?=.*[a-zA-Z])(?=.*\d).{6,}$/,
    message: '密码必须包含字母和数字',
    trigger: 'blur'
  },
  ],
  confirmPassword: [
    { required: true, message: "确认密码不能为空", trigger: "blur" },
    { min: 6, max: 14, message: "确认密码长度为6-14个字符", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== userForm.value.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  phone: [{ required: true, message: "电话不能为空", trigger: "blur" },
  {
    pattern: /^1[3-9]\d{9}$/,
    message: "请输入有效的手机号码",
    trigger: "blur",
  },
  ],
  sex: [{ required: true, message: "性别不能为空", trigger: "blur" }],
  captcha: [{ required: true, message: "验证码不能为空", trigger: "blur" },
  {
    pattern: /^\d{6}$/,
    message: "验证码必须是6位数字",
    trigger: "blur"
  },
  ],
};

const options = [
  {
    value: '男',
    label: '男',
  },
  {
    value: '女',
    label: '女',
  },
]

const isCounting = ref(false);
const countdown = ref(60);

// 发送验证码的逻辑
const sendVerificationCode = async () => {
  if (!userForm.value.phone) {
    ElMessage.error("请先输入手机号");
    return;
  }

  isCounting.value = true;
  countdown.value = 60;

  try {
    const res = await sendSms(userForm.value.phone);
    if (res.code === 1) {
      ElMessage.success("验证码已发送");
    } else {
      ElMessage.error("发送失败，请稍后重试");
    }

    const timer = setInterval(() => {
      if (countdown.value <= 0) {
        clearInterval(timer);
        isCounting.value = false;
      } else {
        countdown.value--;
      }
    }, 1000);
  } catch (error) {
    ElMessage.error("发送失败，请稍后重试");
    isCounting.value = false;
  }
};

// 提交表单处理
const onSubmit = async () => {
  await formRef.value.validate();
  const res = await createAccountAPI(userForm.value);
  if (res.code == 1) {
    ElMessage.success("创建成功");
    dialogVisible.value = false;
  }
};

// 打开对话框并初始化数据
const open = () => {
  dialogVisible.value = true;
  userForm.value = {};
};

// 暴露方法
defineExpose({
  open,
});
</script>